package com.test.profiler

import javax.servlet.http.{HttpServletResponse, HttpServletRequest}
import collection.mutable

object CPUProfilerWebForm{
  def makeForm(req:HttpServletRequest, resp:HttpServletResponse){
    val out = resp.getWriter

    if( req.getParameter("profCPU.clearStats")!=null ){
      CPUProfiler.clearStats()
    }
    if( req.getParameter("profCPU.gatherProfileStats")!=null ){
      var count = Integer.parseInt(req.getParameter("profCPU.count"));
      var delay = Integer.parseInt(req.getParameter("profCPU.delay"));
      var minFrameCount = Integer.parseInt(req.getParameter("profCPU.minFrameCount"));
      if( count<0 ) count=0;
      if( count>500 ) count=500;
      for( i <- 0 until count ){
        CPUProfiler.gatherStatsNow();
        out.println("i="+i+"<br/>");
        out.flush();
        Thread.sleep(delay);
      }
      val res = CPUProfiler.getResult(new FrameStats.Filter(){
        def stop(fs: FrameStats):Boolean = {
              if( fs.getCount<minFrameCount ){
                  return true;
              }
              return false;
        }
      });
      out.println("<pre style='font-size: smaller;' >"+ res +"</pre>")
      out.println("<hr/><h4>Hotspots</h4>");
      val hotSpots: mutable.HashMap[String,Long] = CPUProfiler.hotSpots
      for( h <- hotSpots.toList.sortBy( - _._2).map( _._1 ) ){ // keysSortedDesc()
          out.println(hotSpots(h)+" "+h+"<br/>");
      }

          out.println("<hr/><h4>Hotspots without nested</h4>");
          val hotSpotsNoNest = CPUProfiler.hotSpotsNoNest
          for( h <- hotSpotsNoNest.toList.sortBy( - _._2).map( _._1 ) ){ // keysSortedDesc()
              out.println(hotSpotsNoNest(h)+" "+h+"<br/>");
          }
          out.println("<hr/>");
    }

    val form =
          <form method='post' >
            Profiler iterations:
            <input name="profCPU.count" value="0" /><br/>
            Delay between iterations:
            <input type="text" name="profCPU.delay" value="1000"/><br/>
            Filter: minFrameCount
            <input type="text" name="profCPU.minFrameCount" value="0"/><br/>
            <input type="submit" name='profCPU.gatherProfileStats' value='Add stack traces now' />
            <input type="submit" name='profCPU.clearStats' value='Clear collected stats' />
          </form>
    out.println(form)

  }
}